<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="支付单号" prop="paymentNo">
        <el-input
          v-model="queryParams.paymentNo"
          placeholder="请输入支付单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支付状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择支付状态" clearable>
          <el-option
            v-for="dict in dict.type.rental_payment_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式" prop="paymentMethod">
        <el-select v-model="queryParams.paymentMethod" placeholder="请选择支付方式" clearable>
          <el-option
            v-for="dict in dict.type.rental_payment_method"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付时间" prop="paidTime">
        <el-date-picker clearable
          v-model="queryParams.paidTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:payments:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:payments:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:payments:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:payments:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="paymentsList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
      class="common-table"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="支付单号" align="center" prop="paymentNo" width="150" show-overflow-tooltip />
      <el-table-column label="支付金额" align="center" prop="amount" width="100">
        <template slot-scope="scope">
          <span style="color: #E6A23C; font-weight: bold;">¥{{ scope.row.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付方式" align="center" prop="paymentMethod" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.rental_payment_method" :value="scope.row.paymentMethod"/>
        </template>
      </el-table-column>
      <el-table-column label="支付状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.rental_payment_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="支付时间" align="center" prop="paidTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.paidTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="第三方单号" align="center" prop="thirdPartyNo" width="150" show-overflow-tooltip />
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:payments:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:payments:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改支付记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="支付单号" prop="paymentNo">
              <el-input v-model="form.paymentNo" placeholder="请输入支付单号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单ID" prop="orderId">
              <el-input v-model="form.orderId" placeholder="请输入订单ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户ID" prop="userId">
              <el-input v-model="form.userId" placeholder="请输入用户ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支付方式：1-支付宝，2-微信，3-银行卡，4-余额" prop="paymentMethod">
              <el-input v-model="form.paymentMethod" placeholder="请输入支付方式：1-支付宝，2-微信，3-银行卡，4-余额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支付金额" prop="amount">
              <el-input v-model="form.amount" placeholder="请输入支付金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="第三方支付单号" prop="thirdPartyNo">
              <el-input v-model="form.thirdPartyNo" placeholder="请输入第三方支付单号" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="支付回调信息" prop="callbackInfo">
              <el-input v-model="form.callbackInfo" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支付时间" prop="paidTime">
              <el-date-picker clearable style="width: 100%"
                v-model="form.paidTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择支付时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退款时间" prop="refundTime">
              <el-date-picker clearable style="width: 100%"
                v-model="form.refundTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择退款时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间" prop="createdTime">
              <el-date-picker clearable style="width: 100%"
                v-model="form.createdTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择创建时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新时间" prop="updatedTime">
              <el-date-picker clearable style="width: 100%"
                v-model="form.updatedTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择更新时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPayments, getPayments, delPayments, addPayments, updatePayments } from "@/api/system/payments";

export default {
  name: "Payments",
  dicts: ['rental_payment_type', 'rental_payment_method', 'rental_payment_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 支付记录表格数据
      paymentsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        paymentNo: null,
        orderId: null,
        userId: null,
        paymentType: null,
        paymentMethod: null,
        amount: null,
        status: null,
        thirdPartyNo: null,
        callbackInfo: null,
        paidTime: null,
        refundTime: null,
        createdTime: null,
        updatedTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        paymentNo: [
          { required: true, message: "支付单号不能为空", trigger: "blur" }
        ],
        orderId: [
          { required: true, message: "订单ID不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        paymentType: [
          { required: true, message: "支付类型：1-租金支付，2-押金支付，3-押金退还，4-租金退还不能为空", trigger: "change" }
        ],
        paymentMethod: [
          { required: true, message: "支付方式：1-支付宝，2-微信，3-银行卡，4-余额不能为空", trigger: "blur" }
        ],
        amount: [
          { required: true, message: "支付金额不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "支付状态：1-待支付，2-支付成功，3-支付失败，4-已退款不能为空", trigger: "change" }
        ],
        createdTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updatedTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询支付记录列表 */
    getList() {
      this.loading = true;
      listPayments(this.queryParams).then(response => {
        this.paymentsList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(error => {
        console.error('获取支付记录列表失败:', error);
        this.loading = false;
        this.$modal.msgError('获取支付记录列表失败');
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        paymentId: null,
        paymentNo: null,
        orderId: null,
        userId: null,
        paymentType: null,
        paymentMethod: null,
        amount: null,
        status: null,
        thirdPartyNo: null,
        callbackInfo: null,
        paidTime: null,
        refundTime: null,
        remark: null,
        createdTime: null,
        updatedTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.paymentId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加支付记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const paymentId = row.paymentId || this.ids
      getPayments(paymentId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改支付记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.paymentId != null) {
            updatePayments(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPayments(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const paymentIds = row.paymentId || this.ids;
      this.$modal.confirm('是否确认删除支付记录编号为"' + paymentIds + '"的数据项？').then(function() {
        return delPayments(paymentIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/payments/export', {
        ...this.queryParams
      }, `payments_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
